package com.payment.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.basic.service.contract.IBaseService;
import com.payment.IPaymentBehavior;
import com.translate.entity.NoticeCenter;
import com.translate.entity.Order;
import com.translate.entity.PayManager;
import com.translate.entity.Team;
import com.translate.entity.TeamSigningRewards;
import com.translate.entity.User;
import com.translate.web.config.SpringBeanUtil;
import com.translate.web.constant.OrderErrorMsg;
import com.translate.web.constant.RedisConstant;
import com.translate.web.param.contract.IPayBehaviorRequestParam;
import com.translate.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public class RechargePay<T> extends AbstractPay<T> implements IPaymentBehavior {

	@Autowired
	private ITeamService teamService;

	private interface IPaySuccessCallback {

		public void apply(IPayBehaviorRequestParam behaviorRequestParam, User user);

	}

	private interface IReceivePayManager {

		public PayManager apply(IPayBehaviorRequestParam behaviorRequestParam, User user);

	}

	IReceivePayManager[] receivePayManagers = new IReceivePayManager[] {
			(IPayBehaviorRequestParam behaviorRequestParam, User user) -> {
				IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

				return payManagerService.getPayManager(behaviorRequestParam);
			}, (IPayBehaviorRequestParam behaviorRequestParam, User user) -> {
				IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

				behaviorRequestParam.setUserId(user.getTeamId());

				return payManagerService.getPayManagerByTeam(behaviorRequestParam);
			} };

	IPaySuccessCallback[] successCallback = new IPaySuccessCallback[] {
			(IPayBehaviorRequestParam behaviorRequestParam, User user) -> {

				// 更新支付管理状态
				IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

				payManagerService.paySuccess(behaviorRequestParam);

				// 更新订单状态
				IOrderService orderService = (IOrderService) baseServices[2];

				orderService.paySuccess(behaviorRequestParam);
			},

			(IPayBehaviorRequestParam behaviorRequestParam, User user) -> {

				behaviorRequestParam.setUserId(user.getTeamId());

				// 更新支付管理状态
				IPayManagerService payManagerService = (IPayManagerService) baseServices[0];

				payManagerService.paySuccessByTeam(behaviorRequestParam);

				// 更新订单状态
				IOrderService orderService = (IOrderService) baseServices[2];

				orderService.paySuccessByTeam(behaviorRequestParam);

			} };

	public RechargePay(IBaseService<T>[] baseServices) {
		this.baseServices = baseServices;
	}

	/**
	 * 
	 * 用户端： 编辑端： 管理端： -1 已取消 -1 已取消 0 待报价 待处理 0 待报价 1 已报价 处理中 1 已报价 2 待支付 已返稿 2 待支付
	 * 3 待确认 3 待确认 4 处理中 4 处理中 5 已返稿 5 待派稿 6 待审核 7 未通过 8 已完成 6 已返稿 7 返回编辑确认 8 待审核未通过
	 * 9 已确认 10 已完成
	 */
	@Override
	public int pay(IPayBehaviorRequestParam behaviorRequestParam) {

		// 查询余额 够不够

		IUserService userService = (IUserService) baseServices[1];
		User userData = userService.selectByPrimaryKey((int) behaviorRequestParam.getUserId());



		// 是不是团长
		Byte isRegimental = userData.getIsRegimental();
		

		Integer teamId = userData.getTeamId();

		if (0 == isRegimental && null != teamId && 0 > teamId) {
			throw new IllegalArgumentException("团员不能支付团长的订单");
		}

		PayManager payManager = receivePayManagers[isRegimental].apply(behaviorRequestParam, userData);
		
		BigDecimal academicCurrency = userData.getAcademicCurrency();

		BigDecimal priceSum = payManager.getPriceSum();
		if (-1 == academicCurrency.compareTo(priceSum)) {
			return OrderErrorMsg.INSUFFICIENT_BALANCE.getCode();
		}

		// 扣减余额
		academicCurrency.subtract(priceSum);

		User user = new User();

		user.setAcademicCurrency(academicCurrency.subtract(priceSum));

		user.setUseOfAcademicCoins(userData.getUseOfAcademicCoins().add(priceSum));

		Long teamUserId = userData.getId();
		user.setId(teamUserId);

		userService.updateByPrimaryKeySelective(user);

		// 更新支付管理、及订单状态
		successCallback[isRegimental].apply(behaviorRequestParam, userData);


//		payManagerService.paySuccess(behaviorRequestParam);
//		
//		// 更新订单状态
//		IOrderService orderService = (IOrderService) baseServices[2];
//		
//		orderService.paySuccess(behaviorRequestParam);

		
		// 添加订单记录
		List<Order> ordersByUserIdAndManagerId = orderCallbacks[isRegimental].apply(behaviorRequestParam, userData);

		IOrderLogService logService = (IOrderLogService) baseServices[3];

		int realUserId = teamUserId.intValue();
		
		
		if (1 == isRegimental) {
			
			userData = userService.getUserInfoToCache(payManager.getUserId());
		}
		
		int[] ids = new int[ordersByUserIdAndManagerId.size()];
		
		int i = 0;
		
		Integer serviceId;
		
		byte orderStatus = 2;
		
		NoticeCenter noticeCenter;
		Integer id;
		
		List<NoticeCenter> noticeCenters = new ArrayList<NoticeCenter>();

		long timeMillis = System.currentTimeMillis() / 1000;
		
		for (Order order : ordersByUserIdAndManagerId) {
			
			id = order.getId();
			ids[i] = id;
			
			serviceId = order.getServiceId();
			
			if (9 == serviceId || 10 == serviceId) {
				orderStatus = 14; // 作图
			}
			i++;
			
			noticeCenter = new NoticeCenter();
			
			noticeCenter.setUserId(order.getUserId());
			
			noticeCenter.setTitle("派稿通知  ");
			
			noticeCenter.setNoticeContent("【"+ order.getServiceTypeName() +"】订单"+ order.getOrderSnId() +"进入待派稿，请及时查看处理!");
			
			noticeCenter.setJump((byte) 1);
			
			noticeCenter.setNoticeType((byte) 0);
			
			noticeCenter.setPlatform((byte) 1);
			
			noticeCenter.setTranslateType((byte) 0);
			
			noticeCenter.setTypeId(id);
			
			noticeCenter.setCreateTime(timeMillis);
			
			noticeCenter.setUpdateTime(timeMillis);
			
			noticeCenters.add(noticeCenter);
		}
		
		logService.paySuccessOrderLog(behaviorRequestParam.getId(), realUserId,
				ids, orderStatus);

		// 添加通知
		INoticeCenterService noticeCenterService = (INoticeCenterService) baseServices[5];

		IServiceTypeService serviceTypeService = (IServiceTypeService) baseServices[6];
		
		
		this.generateNoticeData(noticeCenterService, serviceTypeService, ordersByUserIdAndManagerId,
				userData, "已提交，请耐心等待平台处理");
		
		// 处理待派稿
		noticeCenterService.batchInsert(noticeCenters);
		
		IChangeRecordService recordService = (IChangeRecordService) baseServices[4];

		int changeRecord = recordService.addChangeRecord(behaviorRequestParam, priceSum);

//		parseCommission(userService, payManager.getUserId(), changeRecord);

		
		if (null == teamId || 0 == teamId) {
			
			return -600;
			
		}
		// 团长或会员
//		ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringBeanUtil.getBean("threadPoolTaskExecutor");
		
//		IPayManagerService payManagerService = (IPayManagerService) baseServices[0];
		
//		updateDiscount(teamId, threadPoolTaskExecutor, payManagerService);
		
		return changeRecord;

	}

	protected void updateDiscount(Integer teamId, ThreadPoolTaskExecutor threadPoolTaskExecutor,
			IPayManagerService payManagerService) {
		threadPoolTaskExecutor.execute(() -> {
			
			ITeamSigningRewardsService bean = SpringBeanUtil.getBean(ITeamSigningRewardsService.class);

			List<TeamSigningRewards> listToCache = bean.listToCache(RedisConstant.TEAM_SIGN_KEY, 11);
			
			listToCache.sort((f,s) -> s.getPrice().compareTo(f.getPrice()));

			// 余额支付的
			BigDecimal sumPriceByRechargePay = payManagerService.sumPriceByRechargePay(teamId);
			
			
			BigDecimal sumPriceByTeam = payManagerService.sumPriceByTeam(teamId), price = null;
			
			TeamSigningRewards signingRewards = null;
			
			
			for (TeamSigningRewards item : listToCache) {
				
//				Byte type = item.getType();
				
				price = item.getPrice();
				
//				if (1 == type) {
					// 常规 大于及等于
					if(0 < sumPriceByTeam.compareTo(price)) {
						
						signingRewards = item;
						
						break;
					}
					
//				} else if (0 == type) {
					// 以上 无范围 限制
//					if( 0 < sumPriceByTeam.compareTo(price)) {
//						signingRewards = item;
//						break;
//					}
//				}
			}
			
			Team update = new Team();
			
			if (null != signingRewards) {
				update.setDiscount(signingRewards.getDiscount());
			}
			
			
			ITeamService teamService = (ITeamService) baseServices[10];
			
			update.setId(teamId);
			
			update.setCurrency(sumPriceByRechargePay);
			
			teamService.updateByPrimaryKeySelective(update);
		});
	}

//	private void parseCommission(IUserService userService, int userId, int changeRecord) {
//		
//		
//		User userData;
//		
//		// 计算佣金
//		Long recommendedUserId = userData.getRecommendedUserId();
//
//		if (null == recommendedUserId || 0 == recommendedUserId) {
//			return;
//		}
//
//		// 获取推荐配置
//
//		INvitationRewardsConfService revitationRewardsConfService = (INvitationRewardsConfService) baseServices[7];
//
//		List<NvitationRewardsConf> listToCache = revitationRewardsConfService
//				.listToCache(RedisConstant.NVITATION_REWARDS_CONF, 100);
//
//		// 计算推荐了几个人
//
//		int countRecomendNum = userService.countRecomendNum(recommendedUserId);
//
//		NvitationRewardsConf revitationConf = null;
//
//		for (NvitationRewardsConf rewardsConf : listToCache) {
//
//			if (countRecomendNum == rewardsConf.getInvitationNum()) {
//
//				revitationConf = rewardsConf;
//
//				break;
//			}
//		}
//
//		if (null == revitationConf) {
//
//			return;
//		}
//
//		ICommissionManagementService commissionManagementService = (ICommissionManagementService) baseServices[8];
//
//		CommissionManagement commissonManagent = commissionManagementService.getCommissonManagent(recommendedUserId);
//
//		CommissionManagement updateCommissonMan = new CommissionManagement();
//
//		updateCommissonMan.setId(commissonManagent.getId());
//
//		updateCommissonMan.setTotalAmount(commissonManagent.getTotalAmount().add(revitationConf.getRewardAmount()));
//
//		commissionManagementService.updateByPrimaryKeySelective(updateCommissonMan);
//
//		ICommissionManagementDetailService commissionManagementDetailService = (ICommissionManagementDetailService) baseServices[9];
//
//		CommissionManagementDetail commissionManagementDetail = new CommissionManagementDetail();
//
//		commissionManagementDetail.setCommissionId(commissonManagent.getId());
//
//		commissionManagementDetail.setUserId(recommendedUserId.intValue());
//
//		commissionManagementDetail.setDescription("推荐佣金");
//
//		commissionManagementDetail.setMonry(revitationConf.getRewardAmount());
//
//		Long timeMillis = System.currentTimeMillis() / 1000L;
//
//		commissionManagementDetail.setCreateTime(timeMillis);
//
//		commissionManagementDetail.setType((byte) 1);
//
//		commissionManagementDetail.setUpdateTime(timeMillis);
//
//		commissionManagementDetailService.insert(commissionManagementDetail);
//	}
}